package com.hand.pp.interceptor;/**
 * @author Estelle@앙수청
 * @date 2019/7/17 10:25
 */

import com.alibaba.fastjson.JSON;
import com.hand.pp.annotation.PermissionAnnotation;
import com.hand.pp.service.UserService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;

/**
 *  @author Estelle@앙수청
 *  @date 2019/7/17 10:25
 */
@Component
public class ControllerInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Boolean validate = false;
        // 判断是否需要校验的值
        if (isValidate(handler)){
            // 如果为true  调用校验方法
            validate=validateUserPerssion(request);
        }else{
            return true;
        }
        // 判断校验的值
        if (validate){
            return true;
        }else {
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/json");
            response.setStatus(HttpStatus.FORBIDDEN.value());
            ErrorMsg errorMsg = new ErrorMsg("permission.not.found","该用户不存在");
            PrintWriter printWriter = response.getWriter();
            String  msg = JSON.toJSONString(errorMsg);
            printWriter.print(msg);
            printWriter.close();
        }
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("ControllerInterceptor : postHandle" );
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

    /**
     * 判断 是否检验 的值
     * @param handler
     * @return
     */
    private Boolean isValidate(Object handler){
        // 先取出方法
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        // 取方法上的注解
        PermissionAnnotation methodAnnotation = method.getAnnotation(PermissionAnnotation.class);
        // 如果注解不为空  -->  返回注解的值
        if(!StringUtils.isEmpty(methodAnnotation)){
            return methodAnnotation.value();
        }
        else {
            // 否则取类上的注解 --> 返回注解的值
            PermissionAnnotation classAnnotation = method.getDeclaringClass().getAnnotation(PermissionAnnotation.class);
            if(!StringUtils.isEmpty(classAnnotation)){
                return classAnnotation.value();
            }
        }
        // 否则返回false
        return false;
    }

    /**
     * 校验流程
     * @param request
     * @return
     */
    private Boolean validateUserPerssion(HttpServletRequest request){
        boolean result = false;
        // 取头信息
        String id = request.getHeader("id");
        if(!StringUtils.isEmpty(id)){
            // 取出权限的集合  包括path 和 method
            List<Map<String,String>> permissionMap= userService.queryUserPermission(Long.valueOf(id));
            String uri = request.getRequestURI();
            String method = request.getMethod();
            // 比较的工具对象
            AntPathMatcher matcher = new AntPathMatcher();
            for (Map<String,String> map:permissionMap){
                if (matcher.match(map.get("path"), uri)&& map.get("method").equals(method)){
                    //  判断路径和方法是否匹配
                    result = true;
                    break;
                }
            }
        }
        return result;
    }
}
